package com.pool.socket;

import java.io.IOException;
import java.net.*;
import java.util.*;
import com.pool.socket.DataType.*;

import com.pool.socket.DataType.SocketDepict;

public class SocketListener extends Thread {
	SocketServer server;
	protected int listenPort;

	SocketListener(SocketServer server, int listenPort) {
		this.server = server;
		this.listenPort = listenPort;
	}


	private void addSocket(Socket conn) {
		HashMap<Socket, SocketDepict> pool = SocketServer.getSocketPool();
		DataReceiver dataReceiver = new DataReceiver(server,conn);
		SocketDepict description = new SocketDepict(dataReceiver);
		synchronized (pool) {
			pool.put(conn, description);
		}
		dataReceiver.start();
	}

	public void run() {
		try {
			ServerSocket server = new ServerSocket(listenPort, 5);
			server.setReceiveBufferSize(16 * 1024); //set buffer size 16K
			Socket connection = null;
			while (true) {
				connection = server.accept();
				addSocket(connection);
			}
		} catch (BindException e) {
			System.out.println("Unable to bind to port " + listenPort);
		} catch (IOException e) {
			System.out.println("Unable to instantiate a ServerSocket on port: "
					+ listenPort);
		}
	}

}
